#include "../Base/stdafx.h"
#include "Character.h"
#include "../PhysX/PhysX.h"
#include "NxControllerManager.h"
#include "NxCapsuleController.h"
#include "UserAllocator.h"
#include "../Base/DirectInput.h"
#include "../Base/DXDevice.h"
#include "../Base/Camera.h"

#pragma comment(lib, "PhysXLoader.lib")

Character::Character(float posx, float posy, float posz, float height, float radius)
{
	m_LastPos = NxVec3(posx, posy, posz);
	m_Speed = 10;
	// Create actor

	m_Allocator = new UserAllocator();
	m_Manager = NxCreateControllerManager(m_Allocator);
	NxCapsuleControllerDesc desc;
	desc.radius = radius;
	desc.height = height;
	desc.position = NxExtendedVec3(posx, posy, posz);
	desc.climbingMode = CLIMB_EASY;
	m_Controller = m_Manager->createController(PhysX::GetSingleton()->GetScene(), desc);
	m_Controller->setCollision(true);
}

Character::~Character()
{
	NxReleaseControllerManager(m_Manager);
	delete m_Allocator;
}

void Character::move(NxVec3 dir)
{
	NxU32 flags;
	NxVec3 disp = dir;
	m_Controller->move(disp, 1, 0.00001f, flags, 0.5f);
}

NxVec3 Character::GetPosition()
{
	return m_Controller->getActor()->getGlobalPosition();
	//return NxVec3((NxReal)pos.x, (NxReal)pos.y, (NxReal)pos.z);
}

void Character::Tick( float dTime )
{
	static float totalTime = 0;
	totalTime += dTime;

	// Bewegen
	D3DXVECTOR3 dir(0, 0, 0);

	if(DirectInput::GetSingleton()->KeyDown(DIK_W))
		dir += DXDEVICE->GetCamera()->GetLook();
	if(DirectInput::GetSingleton()->KeyDown(DIK_S))
		dir -= DXDEVICE->GetCamera()->GetLook();
	if(DirectInput::GetSingleton()->KeyDown(DIK_A))
		dir -= DXDEVICE->GetCamera()->GetRight();
	if(DirectInput::GetSingleton()->KeyDown(DIK_D))
		dir += DXDEVICE->GetCamera()->GetRight();

	D3DXVec3Normalize(&dir, &dir);

	if(DirectInput::GetSingleton()->KeyDown(DIK_LSHIFT))
		dir *= 5;

	dir *= m_Speed * dTime;

	move(NxVec3(dir.x, dir.y, dir.z));

	// Zwaartekracht
	float speed = m_CurrSpeed.y;

	if(speed < 0.1f)
		speed = 0.1f;
	else{
		speed += (9.81f * dTime);
	}
	if(DirectInput::GetSingleton()->KeyDown(DIK_SPACE))
		speed = -10 * dTime;

	move(NxVec3(0, -speed, 0));

	// Calculate speed
	float x = (GetPosition().x - m_LastPos.x) / dTime;
	float y = (GetPosition().y - m_LastPos.y) / dTime;
	float z = (GetPosition().z - m_LastPos.z) / dTime;
	m_CurrSpeed = D3DXVECTOR3(x, y, z);
	
	m_LastPos = GetPosition();
}

const D3DXVECTOR3& Character::GetSpeed() const
{
	return m_CurrSpeed;
}